let url = '/treeHole/user.action'
let userUrl = '/treeHole/user.action'
import api from './global.js'

let Interval;
let timeOut = 300;
let faceInterval;
let i = false;
let j = 0;
new Vue({
    el: "#app",
    data: {
        userTelPhoneOrEmail: '',
        userPassword: '',
        userTelephoneNumber: '',
        new_userPassword: '',
        re_userPassword: '',
        valCode: '',
        isDisabled: true,
        isDisabled2: true,
        smsword: '发送验证码',
        drawer: false,
        isOpen: false,
        openFail: false
    },
    methods: {
        uploadImg() {
            if (this.openFail == true) {
                clearInterval(faceInterval);
                return;
            }
            j++;
            if (j > 15) {
                clearInterval(faceInterval);
                this.$message.error("登录失败");
                this.closeCamera();
                this.drawer = false;
                j = 0;
                return;
            }
            let ctx = this.$refs['canvas'].getContext('2d');
            ctx.drawImage(this.$refs['video'], 0, 0, 400, 300);
            let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7);
            let str = imgBase64.replace('data:image/jpeg;base64,', '');
            let params = new URLSearchParams();
            params.append("op", "loginFace");
            params.append("base64", str);
            axios.post(userUrl, params).then(res => {
                if (res.data.code == '200') {
                    clearInterval(faceInterval);
                    this.closeCamera();
                    res = res.data.data;
                    this.drawer = false;
                    this.$message({
                        type: "success",
                        message: '登录成功，2s后自动跳转至首页',
                        center: true
                    });
                    api.setCookie("loginUser.userId", res.loginUser.userId);
                    api.setCookie("loginUser.userName", res.loginUser.userName);
                    api.setCookie("loginUser.userProfilePhoto", res.loginUser.userProfilePhoto);
                    api.setCookie("loginUser.userRegistrationTime", res.loginUser.userRegistrationTime);
                    api.setCookie("loginUser.userTelephoneNumber", res.loginUser.userTelephoneNumber);
                    api.setCookie("token", res.token);
                    setTimeout(this.jumpPage, 2000);
                } else {
                    if (j > 15) {
                        this.$message.error("登录失败");
                        return;
                    }
                }
            });
        },
        sleep(numberMillis) {
            var now = new Date();
            var exitTime = now.getTime() + numberMillis;
            while (true) {
                now = new Date();
                if (now.getTime() > exitTime)
                    return;
            }
        },
        closeCamera() {
            if (!this.$refs['video'].srcObject) return;
            let stream = this.$refs['video'].srcObject;
            let tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop();
            });
            this.$refs['video'].srcObject = null;
        }
        ,
        closeFaceLogin() {
            this.drawer = false;
            this.closeCamera();
            clearInterval(faceInterval);
            j = 0;
        }
        ,
        getUserMedia(constraints, success, error) {
            if (navigator.mediaDevices.getUserMedia) {
                //最新的标准API
                navigator.mediaDevices.getUserMedia(constraints).then(success => {
                    // 摄像头开启成功
                    this.$refs['video'].srcObject = success
                    // 实时拍照效果
                    this.$refs['video'].play()
                }).catch(error);

            } else if (navigator.webkitGetUserMedia) {
                //webkit核心浏览器
                navigator.webkitGetUserMedia(constraints, success, error)
            } else if (navigator.mozGetUserMedia) {
                //firfox浏览器
                navigator.mozGetUserMedia(constraints, success, error);
            } else if (navigator.getUserMedia) {
                //旧版API
                navigator.getUserMedia(constraints, success, error);
            }
        }
        ,
        callCamera() {
            try {
                navigator.mediaDevices.getUserMedia({
                    video: true
                }).then(success => {
                    this.$refs['video'].srcObject = success;
                    this.$refs['video'].play();
                    this.isOpen = true;
                }).catch(error => {
                    this.drawer = false;
                    this.openFail = true;
                    this.$message({
                        message: '摄像头开启失败，请检查摄像头是否可用！由于浏览器安全策略，开启摄像功能只支持https协议。解决方法:使用谷歌浏览器，并参考博文：https://www.cnblogs.com/aaronguo/p/14204962.html',
                        center: true,
                        type: 'warning',
                        duration: 20000,
                        showClose: true
                    });
                })
            } catch (e) {
                this.drawer = false;
                this.openFail = true;
                this.$message({
                    message: '摄像头开启失败，请检查摄像头是否可用！由于浏览器安全策略，开启摄像功能只支持https协议。解决方法:使用谷歌浏览器，并参考博文：https://www.cnblogs.com/aaronguo/p/14204962.html',
                    center: true,
                    type: 'warning',
                    duration: 20000,
                    showClose: true
                });
            }
        }
        ,
        faceLogin() {
            this.drawer = true;
            setTimeout(this.callCamera(), 200);
            // if (this.isOpen == true) {
            faceInterval = setInterval(this.uploadImg, 1000);
            // } else {
            //     this.drawer = false;
            // }
        }
        ,
        switchBtn() {
            document.querySelector('.content').classList.toggle('s--signup')
        }
        ,
        login() {
            let params = new URLSearchParams()
            params.append("op", "login");
            params.append("userTelPhoneOrEmail", this.userTelPhoneOrEmail);
            params.append("userPassword", this.userPassword);
            axios.post(url, params).then(res => {
                res = res.data.data;
                if (res.isLogin == true) {
                    this.$message({
                        type: "success",
                        message: '登录成功，2s后自动跳转至首页',
                        center: true
                    });

                    api.setCookie("loginUser.userId", res.loginUser.userId);
                    api.setCookie("loginUser.userName", res.loginUser.userName);
                    api.setCookie("loginUser.userProfilePhoto", res.loginUser.userProfilePhoto);
                    api.setCookie("loginUser.userRegistrationTime", res.loginUser.userRegistrationTime);
                    api.setCookie("loginUser.userTelephoneNumber", res.loginUser.userTelephoneNumber);
                    api.setCookie("token", res.token);
                    setTimeout(this.jumpPage, 2000);
                } else {
                    this.$message({
                        type: "error",
                        message: '账号或密码错误',
                        center: true
                    });
                }
            })
        }
        ,
        jumpPage() {
            window.location.href = "index.html";
            // window.close();
        }
        ,
        register() {
            var params = new URLSearchParams()
            params.append("op", "validationSmsCode");
            params.append("telPhone", this.userTelephoneNumber);
            params.append("smsCode", this.valCode);
            axios.post('/treeHole/SmsCode.action', params).then(res => {
                if (res.data.data.varIsOk == false) {
                    //说明验证码错误
                    this.$message({
                        type: "error",
                        message: '验证码错误',
                        center: true
                    });
                    this.isDisabled2 = true;
                    return;
                } else {
                    //说明验证码正确
                    this.isDisabled2 = false;
                    var params = new URLSearchParams()
                    params.append("op", "register");
                    params.append("userTelephoneNumber", this.userTelephoneNumber);
                    params.append("userPassword", this.new_userPassword);
                    axios.post(url, params).then(res => {
                        if (res.data.data.isLogin == true) {
                            //注册成功
                            this.$message({
                                type: "success",
                                message: '注册成功，即将返回首页',
                                center: true
                            });
                            res = res.data.data;
                            api.setCookie("loginUser.userId", res.loginUser.userId);
                            api.setCookie("loginUser.userName", res.loginUser.userName);
                            api.setCookie("loginUser.userProfilePhoto", res.loginUser.userProfilePhoto);
                            api.setCookie("loginUser.userRegistrationTime", res.loginUser.userRegistrationTime);
                            api.setCookie("loginUser.userTelephoneNumber", res.loginUser.userTelephoneNumber);
                            api.setCookie("token", res.token);
                            setTimeout(this.jumpPage, 2000);
                        } else {
                            //注册失败
                            this.$message({
                                type: "error",
                                message: '注册失败',
                                center: true
                            });
                        }

                    });
                }
            })
        }
        ,
        checkTel() {
            if (this.userTelephoneNumber == '') {
                this.isDisabled = true;
                return;
            }
            let reg = /^([1][3,4,5,6,7,8,9])\d{9}$/;
            let isOk = reg.test(this.userTelephoneNumber);
            if (!isOk) {
                this.$message({
                    type: "warning",
                    message: '请输入有效的手机号',
                    center: true
                });
                this.isDisabled = true;
                this.isDisabled2 = true;
                return;
            }
            let params = new URLSearchParams()
            params.append("op", "checkTelIsOk");
            params.append("userTelephoneNumber", this.userTelephoneNumber);
            axios.post(url, params).then(res => {
                res = res.data.data;
                if (res) {
                    this.$message({
                        type: "success",
                        message: '手机号可以用',
                        center: true
                    });
                    this.isDisabled = false;
                    this.isDisabled2 = false;
                } else {
                    this.$message({
                        type: "error",
                        message: '手机号已经被注册',
                        center: true
                    });
                    this.isDisabled = true;
                    this.isDisabled2 = true;
                }
            })
        }
        ,
        checkPassword(index) {
            if (this.new_userPassword == '') {
                this.$message({
                    type: "warning",
                    message: '密码不能为空',
                    center: true
                });
                this.isDisabled2 = true;
                return;
            }
            if (index == 1) {
                if (this.new_userPassword.length < 6) {
                    this.$message({
                        type: "warning",
                        message: '密码长度再长一点',
                        center: true
                    });
                    this.isDisabled2 = true;
                    return;
                }
            } else {
                if (this.new_userPassword.length < 6) {
                    this.$message({
                        type: "warning",
                        message: '密码长度再长一点',
                        center: true
                    });
                    this.isDisabled2 = true;
                    return;
                }
                if (this.new_userPassword != this.re_userPassword) {
                    this.$message({
                        type: "warning",
                        message: '两次密码不一致',
                        center: true
                    });
                    this.isDisabled2 = true;
                    return;
                }
                this.$message({
                    type: "success",
                    message: '密码可以用',
                    center: true
                });
                this.isDisabled2 = false;
            }
        }
        ,
        sendSms() {
            let params = new URLSearchParams()
            params.append("op", "getSmsCode");
            params.append("telPhone", this.userTelephoneNumber);
            axios.post('/treeHole/SmsCode.action', params).then(res => {
                if (res.data.data.theTelPhoneIsOk == false) {
                    //说明手机号已经被注册
                    this.$message({
                        type: "error",
                        message: '手机号已经被注册',
                        center: true
                    });
                    this.isDisabled2 = true;
                    return;
                } else {
                    if (res.data.data.isSendOk == true) {
                        //说明短信发送成功
                        this.$message({
                            type: "success",
                            message: '短信发送成功，5分钟内有效，不区分大小写',
                            center: true
                        });
                        this.isDisabled = true;
                        this.isDisabled2 = false;
                        Interval = setInterval(this.showTime, 1000)
                    } else {
                        this.$message({
                            type: "error",
                            message: '短信发送失败，请稍后再试',
                            center: true
                        });
                        this.isDisabled2 = true;
                        return;
                    }

                }
            })
        },
        showTime() {
            if (timeOut-- <= 0) {
                this.isDisabled = false;
                this.smsword = "再次发送";
                clearInterval(Interval)
                timeOut = 300;
            } else {
                this.smsword = timeOut + " s再次发送"
            }
        }
        ,


    },
    mounted() {

    }
})
;